package cn.eports.learn.web.servlet;

import cn.eports.learn.domain.User;
import cn.eports.learn.service.UserService;
import cn.eports.learn.service.impl.UserServiceImpl;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;


@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        super.doPost(req, resp);

//        PrintWriter writer = resp.getWriter();

        //1. 设置编码
        req.setCharacterEncoding("utf-8");

        // 2. 获取用户输入的验证码
        String verifycode = req.getParameter("verifycode");

        // 获取验证码，校验验证码
        final HttpSession session = req.getSession();
        final String checkcode_server = (String) session.getAttribute("CHECKCODE_SERVER");

        // 移除验证码，确保验证码的一次性
        session.removeAttribute("CHECKCODE_SERVER");
        // 如果验证码不正确
        if (!checkcode_server.equalsIgnoreCase(verifycode)){

            // 提示信息
            req.setAttribute("login_msg", "验证码错误！");
            // 跳转登录页面
            req.getRequestDispatcher("/login.jsp").forward(req, resp);

            return;
        }

        Map<String, String[]> map = req.getParameterMap();

        // 3. 封装User对象
        User user = new User();
        try {
            BeanUtils.populate(user, map);

        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        // 4. 调用Service查询
        UserService service = new UserServiceImpl();
        User loginUser = service.login(user);
        System.out.println("loginUser: " + loginUser.toString());
        // 5. 判断是否登录成功
        if (loginUser != null) {
            // 登录成功，将用户存入session
            session.setAttribute("user", loginUser);
            // 跳转页面
            resp.sendRedirect(req.getContextPath() + "/index.jsp");
        } else {
            // 登录失败
            // 提示信息
            req.setAttribute("login_msg", "用户名或密码错误！");
            // 跳转登录页面
            req.getRequestDispatcher("/login.jsp").forward(req, resp);
        }
    }
}
